package org.support.small.infrastructure;

import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import org.reflections.Reflections;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Set;

@Configuration
public class AuditDomainFlexConfiguration implements MyBatisFlexCustomizer {
    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        // 列出所有的继承AuditDomain的类
        Reflections reflections = new Reflections("org.support.small.infrastructure");
        Set<Class<? extends AuditDomain>> classes = reflections.getSubTypesOf(AuditDomain.class);
        Class[] auditDomainChildren = classes.toArray(new Class[0]);
        flexGlobalConfig.registerInsertListener(new AuditDomainInsertListener(), auditDomainChildren);
        flexGlobalConfig.registerUpdateListener(new AuditDomainUpdateListener(), auditDomainChildren);
    }

    public static final class AuditDomainInsertListener implements InsertListener {
        @Override
        public void onInsert(Object entity) {
            if (AuditDomain.class.isAssignableFrom(entity.getClass())) {
                AuditDomain auditDomain = (AuditDomain) entity;
                auditDomain.setCreateTime(LocalDateTime.now());
                auditDomain.setUpdateTime(LocalDateTime.now());
                auditDomain.setCreateBy("1");
                auditDomain.setUpdateBy("1");
            }
        }
    }

    public static final class AuditDomainUpdateListener implements UpdateListener {
        @Override
        public void onUpdate(Object entity) {
            if (AuditDomain.class.isAssignableFrom(entity.getClass())) {
                AuditDomain auditDomain = (AuditDomain) entity;
                auditDomain.setUpdateTime(LocalDateTime.now());
                auditDomain.setUpdateBy("1");
                auditDomain.setDeleteFlag(false);
            }
        }
    }
}
